package com.ygqh.baby.service.wdtqyb.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.handler.FortuneBagHandler;
import com.ygqh.baby.model.wdt.qyb.WdtQybOrderLstReq;
import com.ygqh.baby.model.wdt.qyb.WdtQybOrderReq;
import com.ygqh.baby.model.wdt.qyb.WdtQybResult;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgSkuService;
import com.ygqh.baby.service.YgSupplierService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.wdtqyb.exception.WdtException;
import com.ygqh.baby.service.wdtqyb.http.WdtResponse;
import com.ygqh.baby.service.wdtqyb.util.WDTConfigure;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class WdtQybBaseApi extends MpApi {
    protected final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private YgSkuService ygSkuService;
    @Autowired
    private YgProductService ygProductService;

    @Value("${mail.to.all}")
    protected String mailToAll;
    @Value("${mail.to.js}")
    protected String mailToJS;
    @Value("${sms.isSend}")
    protected Boolean isSend;
    @Autowired
    protected YgSupplierService ygSupplierService;
    @Autowired
    protected YgUserService ygUserService;
    @Autowired
    protected FortuneBagHandler fortuneBagHandler;

    public WdtQybBaseApi() {
        super();
    }

    protected String getShopNo() {
        return getRequestUri(WDTConfigure.SHOP_NO);
    }

    /**
     * 推送订单到旺店通企业版
     *
     * @return WdtQybResult 返回类型
     * @throws WdtException 入参
     * @throws @date        2017年8月8日 下午3:09:39
     * @Title: TradePush
     * @author （guohao）
     * @version V1.0
     */
    protected WdtQybResult tradePush(String shopNo, WdtQybOrderReq orderReq) throws WdtException {
        if (orderReq == null) {
            return new WdtQybResult(1, "推送明细为空，不予推送");
        }
        return tradePush(shopNo, Collections.singletonList(orderReq));
    }

    protected WdtQybResult tradePush(String shopNo, List<WdtQybOrderReq> orderReq) throws WdtException {
        if (CollectionUtils.isEmpty(orderReq)) {
            return new WdtQybResult(1, "推送明细为空，不予推送");
        }
        String orderInfo = JSON.toJSONString(orderReq);
        // 系统级别参数
        Map<String, String> param = getApplicationParam();
        // 接口级别参数
        param.put("shop_no", shopNo);
        param.put("trade_list", orderInfo);
        // 获取签名
        String sign = getSign(param);
        param.put("sign", sign);
        // 获取api路径
        String apiUrl = getRequestUri("trade_push_uri");

        WdtResponse wdtResponse = wdtRequestExecutor.post(apiUrl, param);

        return wdtResponse.getAsObject(new TypeReference<WdtQybResult>() {
        });
    }

    protected WdtQybResult baseTradePush(List<WdtQybOrderReq> orderList) throws WdtException {
        String orderInfo = JSON.toJSONString(orderList);
        // 系统级别参数
        Map<String, String> param = getApplicationParam();
        // 接口级别参数
        param.put("shop_no", getRequestUri(WDTConfigure.SHOP_NO));
        param.put("trade_list", orderInfo);
        // 获取签名
        String sign = getSign(param);
        param.put("sign", sign);

        // 获取api路径
        String apiUrl = getRequestUri("trade_push_uri");
        System.out.println(param.toString());
        WdtResponse wdtResponse = wdtRequestExecutor.post(apiUrl, param);
        System.out.println(wdtResponse.getAsString());

        return wdtResponse.getAsObject(new TypeReference<WdtQybResult>() {
        });
    }

    /**
     * 获取订单的总优惠金额
     *
     * @param order
     * @return BigDecimal 返回类型
     * @throws @date 2017年8月17日 上午11:33:50
     * @Title: getOrderDisPrice
     * @author （guohao）
     * @version V1.0
     */
    protected BigDecimal getOrderDisPrice(YgOrder order) {
        BigDecimal discountPrice = order.getAccountPrice().add(order.getManjianPrice()).add(order.getNewCustomDisPrice()).add(order.getYouhuijuanPrice())
                .add(order.getPackDisPrice());
        BigDecimal realDis = order.getProductPrice().add(order.getExpressPrice()).subtract(order.getTotalPrice());
        System.out.println(discountPrice.toString());
        System.out.println(discountPrice.toString());
        if (discountPrice.compareTo(realDis) > 0) {
            discountPrice = realDis;
        }
        return discountPrice;
    }

    /**
     * 获取分摊优惠金额
     *
     * @param disPrice
     * @param orderPrice
     * @param salePrice  入参
     * @return BigDecimal 返回类型
     * @throws @date 2017年9月11日 下午2:12:09
     * @Title: getShareDisPrice
     * @author （guohao）
     * @version V1.0
     */
    protected BigDecimal getShareDisPrice(BigDecimal disPrice, BigDecimal orderPrice, BigDecimal salePrice) {
        if (disPrice.intValue() == 0) {
            return disPrice;
        }
        BigDecimal price = disPrice.multiply(salePrice).divide(orderPrice, 2, BigDecimal.ROUND_HALF_UP);
        return price;
    }

    protected WdtQybOrderReq getTradePushInfo(YgOrder order) {
        fortuneBagHandler.reassemblyOrderDetails(order);

        List<WdtQybOrderLstReq> detailList = new ArrayList<WdtQybOrderLstReq>();
        int orderStatus = 30;
        // 付款状态:0未付款1部分付款2已付款
        String payStatus = "2";
        String paid;
        Date paidTime = order.getPaidTime();
        if (order.getOrderStatus().equals(OrderStatus.TradeClosed)) {
            orderStatus = 80;
        } else if (order.getOrderStatus().equals(OrderStatus.WaitingPay)) {
            orderStatus = 10;
            payStatus = "1";
            paidTime = null;
        }

        BigDecimal discountPrice = this.getOrderDisPrice(order);
        List<YgOrderDetail> orderDetail = order.getOrderDetail();

        BigDecimal lastDisPrice = discountPrice;

        List<YgOrderDetail> collect = getOrderDetailOnlyYiigoo(orderDetail);
        if (CollectionUtils.isEmpty(collect)) {
            return null;
        }
        // 订单明细
        BigDecimal totalPrice = new BigDecimal(0);
        for (int i = 0; i < collect.size(); i++) {
            YgOrderDetail detail = collect.get(i);
            BigDecimal shareDisPrice;
            if (i == collect.size() - 1) {
                shareDisPrice = lastDisPrice;
            } else {
                shareDisPrice = this.getShareDisPrice(discountPrice, order.getProductPrice(),
                        detail.getSalePrice().multiply(new BigDecimal(detail.getQuantity())));
                lastDisPrice = lastDisPrice.subtract(shareDisPrice);
            }
            BigDecimal skuprice = detail.getSalePrice().multiply(new BigDecimal(detail.getQuantity())).subtract(shareDisPrice);
            if (skuprice.compareTo(BigDecimal.ZERO) < 0) {
                shareDisPrice = new BigDecimal("0.00");
                skuprice = detail.getSalePrice().multiply(new BigDecimal(detail.getQuantity()));
            }
            totalPrice = totalPrice.add(skuprice);

            YgSku sku = ygSkuService.findById(detail.getSkuId());
            YgProduct product = ygProductService.findById(sku.getProductId());

            WdtQybOrderLstReq lstReq = new WdtQybOrderLstReq(order.getOrderId() + "-" + detail.getId(), new BigDecimal(detail.getQuantity()),
                    detail.getSalePrice(), 30, 0, product.getProductCode(), product.getProductName(), detail.getSkuCode(),
                    product.getShortName() + " " + sku.getSizeName(), "");
            lstReq.setShareDiscount(shareDisPrice);
            detailList.add(lstReq);

        }
        paid = totalPrice.add(order.getExpressPrice()).toString();
        // 订单主信息
        WdtQybOrderReq orderReq = new WdtQybOrderReq(order.getOrderId().toString(), orderStatus, 1, payStatus, order.getReceiver(), order.getProvinceName(),
                order.getCityName(), order.getAreaName(), order.getAddress(), "-1", order.getExpressPrice().toString(), "0", "0", "0", paid.toString(),
                detailList);
        if (StringUtil.isBlank(order.getUserName())) {
            YgUser user = ygUserService.findById(order.getUserId());
            order.setUserName(user.getUserName());
        }
        orderReq.setBuyerNick(order.getUserName());
        orderReq.setBuyerMessage(order.getUserRemark());
        orderReq.setReceiverMobile(order.getTelPhone());
        orderReq.setTradeTime(order.getCreateTime());
        orderReq.setPayTime(paidTime);
        if (StringUtils.isBlank(order.getUserName())) {
            YgUser user = ygUserService.findById(order.getUserId());
            String userName = user.getUserName();
            if (userName.length() > 12) {
                userName = userName.substring(0, 11);
            }
            order.setUserName(userName);
        }
        orderReq.setBuyerNick(order.getUserName());
        orderReq.setSellerMemo(order.getPlatformName());

        return orderReq;
    }

    protected List<YgOrderDetail> getOrderDetailOnlyYiigoo(List<YgOrderDetail> orderDetail) {
        Map<Long, List<YgOrderDetail>> orderMap = orderDetail.stream().collect(Collectors.groupingBy(YgOrderDetail::getSupplierId));
        List<YgOrderDetail> syncDetailList = new ArrayList<>();
        for (Map.Entry<Long, List<YgOrderDetail>> entry : orderMap.entrySet()) {
            if (ygSupplierService.isSyncWDT(entry.getKey())) {
                syncDetailList.addAll(entry.getValue());
            }
        }
        return syncDetailList;
    }

}
